using System.Text.Json;
using System.Text.Json.Nodes;

namespace YMJake.Flowable.ExternalWorker.Client.Core.Variables;

/// <summary>
/// Represents a JSON variable in Flowable
/// </summary>
public sealed record JsonVariable(JsonNode Value) : VariableBase
{
    public override string TypeName => "json";
    public override object RawValue => Value;

    /// <summary>
    /// Create a JSON variable from any object
    /// </summary>
    public static JsonVariable Create<T>(T value, JsonSerializerOptions? options = null)
    {
        var jsonNode = JsonSerializer.SerializeToNode(value, options)
                       ?? throw new ArgumentException("Given object could not be serialized to json", nameof(value));

        return new JsonVariable(jsonNode);
    }

    /// <summary>
    /// Parse the JSON variable to a specific type
    /// </summary>
    public T? Parse<T>(JsonSerializerOptions? options = null)
    {
        return Value.Deserialize<T>(options);
    }
}